package utils

import (
	"encoding/json"
	"reflect"

	"gitee.com/sansaniot/ssiot-core/logger"
	"github.com/mitchellh/mapstructure"
)

func ConvtByteToStruct(source []byte, res interface{}) {
	err := json.Unmarshal(source, &res)
	if err != nil {
		logger.Error(err)
	}
}

func ConvtByteToMap(source []byte, res interface{}) {
	err := json.Unmarshal(source, &res)
	if err != nil {
		logger.Error(err)
	}
}

// map转结构体
func ConvtMapToStruct(source interface{}, res interface{}) {
	err := mapstructure.Decode(source, &res)
	if err != nil {
		logger.Error(err)
	}
}
func ConvtStructToMap(data interface{}, m map[string]interface{}) {
	objT := reflect.TypeOf(data)
	objV := reflect.ValueOf(data)
	for i := 0; i < objT.NumField(); i++ {
		if jf, ok := objT.Field(i).Tag.Lookup("json"); ok {
			if jf == "-" {
				continue
			}
			m[jf] = objV.Field(i).Interface()
		} else {
			m[objT.Field(i).Name] = objV.Field(i).Interface()
		}

	}
}

func ConvtJsonToMap(source string, m interface{}) {
	err := json.Unmarshal([]byte(source), &m)
	if err != nil {
		logger.Error(err)
	}
}
func ConvtMapToJson(source interface{}, res *string) {
	jsonByte, err := json.Marshal(source)
	if err != nil {
		logger.Error(err)
	}
	*res = string(jsonByte)
}
func ConvtJsonToStruct(source string, res interface{}) {
	if err := json.Unmarshal([]byte(source), &res); err == nil {
		logger.Error(err)
	}
}
func ConvtStructToJson(source interface{}, res *string) {
	b, err := json.Marshal(source)
	if err != nil {
		logger.Error(err)
	}
	*res = string(b)
}
func GetMapKeys(m map[string]interface{}) []string {
	// 数组默认长度为map长度,后面append时,不需要重新申请内存和拷贝,效率很高
	j := 0
	keys := make([]string, len(m))
	for k := range m {
		keys[j] = k
		j++
	}
	return keys
}
